package servletAction;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.context.ApplicationContext;

import util.DomainUtils;
import util.FormArgumentsException;
import domain.dao.interfaces.IDAOContact;
import domain.dao.interfaces.IDAOContactGroup;
import actionForm.AddContactGroupValidationForm;
import actionForm.AddToContactGroupValidationForm;

public class AddToContactGroupAction extends Action{
	

	public ActionForward execute(final ActionMapping pMapping,
			ActionForm pForm, final HttpServletRequest pRequest,
			final HttpServletResponse pResponse) {

		ApplicationContext context = util.SpringUtils.getApplicationContext();
		final AddToContactGroupValidationForm lForm = (AddToContactGroupValidationForm) pForm;
		
		String[] contacts_to_add = lForm.getContacts_to_add();
		String selected_contactgroup =lForm.getSelected_contactgroup();
		IDAOContactGroup daoContactGroup = null;
		IDAOContact daoContact = null;
		int idContactGroup = -1; 
		
		
		
		try {
			
			daoContactGroup = (IDAOContactGroup) context.getBean("beanDAOContactGroup");
			daoContact =(IDAOContact) context.getBean("beanDAOContact");
			
			
			idContactGroup = Integer.parseInt(selected_contactgroup);
			daoContactGroup.addContactsToGroup(idContactGroup, contacts_to_add);
			
			
			DomainUtils.displayInfoMessage(
					pRequest, 
					DomainUtils.ADD_CONTACT_GROUP_ALERT_CURRENT_COLOR, 
					"Specified contacts had been added successfully.");
		}
		catch(Exception e) {
			
			boolean someContactsAreMissing = false;
			
			for(String strIdContact : contacts_to_add) {
				if(daoContact.getById(Integer.parseInt(strIdContact)) == null){
					someContactsAreMissing = true;
					break;
				}
			}
			
			
			if(someContactsAreMissing) {
				pRequest.setAttribute(
						DomainUtils.ALERT_ERROR_STRING, 
						"Some contacts had been conccurently deleted.");
			}
			else if((e instanceof FormArgumentsException) == false) {
				pRequest.setAttribute(DomainUtils.ALERT_ERROR_STRING, 
						"An error occur on the server.");
			}	
			
			DomainUtils.keepParametersContent(pRequest);
		}
		

		return pMapping.findForward("stay");

	}

}
